﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Tec2.GUI.Controls
{
	public class RadioPanel : Panel
	{

		#region Members

		public event EventHandler SelectedChanged = delegate { };
		int selected;

		#endregion

		#region Properties

		public int Selected
		{
			get
			{
				return selected;
			}
			set
			{
				int val = 0;
				var radioButton = this.Controls.OfType<RadioButton>()
				    .FirstOrDefault(radio =>
					  radio.Tag != null
					 && int.TryParse(radio.Tag.ToString(), out val) && val == value);

				if (radioButton != null)
				{
					radioButton.Checked = true;
					selected = val;
				}
			}
		}

		#endregion

		#region Methods

		protected override void OnControlAdded(ControlEventArgs e)
		{
			base.OnControlAdded(e);

			var radioButton = e.Control as RadioButton;
			if (radioButton != null)
				radioButton.CheckedChanged += radioButton_CheckedChanged;
		}

		void radioButton_CheckedChanged(object sender, EventArgs e)
		{
			var radio = (RadioButton)sender;
			int val = 0;
			if (radio.Checked && radio.Tag != null
			     && int.TryParse(radio.Tag.ToString(), out val))
			{
				selected = val;
				SelectedChanged(this, new EventArgs());
			}
		}

		#endregion

	}
}
